<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\RowActions\DisPatchAction;
use App\Admin\Actions\Grid\RowActions\ProjectOverAction;
use App\Admin\Repositories\Company;
use App\Admin\Repositories\ContractTemplate;
use App\Admin\Repositories\Project;
use App\Models\Project as AppProject;
use App\Support\Data;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;

class StatisticsPayTaxesController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AppProject(), function (Grid $grid) {
            $grid->disableViewButton();
            $grid->disableEditButton();
            $grid->disableDeleteButton();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableRowSelector();
            $grid->disablePerPages();
            $grid->paginate(10);

            $grid->model()->orderBy('id', 'desc');

            $grid->column('id')->sortable();
            $grid->scrollbarX();

            $grid->column('project_name');

            $grid->column('税后金额')->display(function () {
                return Data::getProjectAfterTaxAmount($this->id);
            });
            $grid->column('人次')->display(function () {
                return Data::getProjectNumberOfPeople($this->id);
            });;




            $grid->filter(function (Grid\Filter $filter) {

                $filter->like('project_name');
                $filter->equal('created_at')->date(); //('created_at');
                // $filter->equal('created_at')->month();
                // $filter->month('created_at');
            });

            // 管理员和创建人可以设置分配
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $currLoginUser = auth('admin')->user();

                if (Admin::user()->isAdministrator() || Admin::user()->isRole('财务管理')) {

                    // append一个操作
                    $actions->append('<a href="/user/list?project_id=' . $actions->row->id . '" class="text-custom" style="margin-right: 10px;">明细</a>');

                    // $actions->append(new DisPatchAction()); // 分配

                    // $actions->append(new ProjectOverAction()); // 项目完结
                }
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Project(), function (Show $show) {
            $show->field('id');
            $show->field('project_name');
            $show->field('project_sn');
            $show->field('active_name');
            $show->field('sponsor');
            $show->field('company');
            $show->field('company_short');
            // $show->field('is_contract');
            $show->field('status');
            $show->field('fee_type');
            $show->field('master_user_id');
            $show->field('master_user_name');
            $show->field('worker_user_id');
            $show->field('worker_user_name');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Project(), function (Form $form) {
            $form->display('id');
            $form->select('company_id', '所属公司')
                ->options(Company::getCompanyList())
                ->required();
            $form->text('project_name')->required();
            $form->text('project_sn')->required();
            $form->text('active_name')->required();
            $form->text('sponsor');
            $form->text('company');
            $form->text('company_short');



            if ($form->isCreating()) {
                $form->hidden('master_user_id');
                $form->hidden('master_user_name');
                $form->hidden('project_code');

                $checkBoxItem = '';
                $feeTypeOptions = Project::getFeeTypeOptions();
                foreach ($feeTypeOptions as $feeTypeID => $feeTypeName) {
                    $checkBoxItem .= '<div class="item" style="float: left; margin-right: 10px;">
                                    <div class="vs-checkbox-con vs-checkbox-primary" style="margin-right: 16px">
                                        <input value="' . $feeTypeID . '" name="fee_type[]" class="field_fee_type _normal_ Dcat_Admin_Widgets_Checkbox" type="checkbox" initialized="" id="' . time() . $feeTypeID . '">
                                        <span class="vs-checkbox vs-checkbox-">
                                            <span class="vs-checkbox--check">
                                                <i class="vs-icon feather icon-check"></i>
                                            </span>
                                        </span>
                                        <span>' . $feeTypeName . '</span>
                                    </div>
                                    <input type="text" name="fee_type_' . $feeTypeID . '" placeholder="请输入税后金额" >
                                </div>   ';
                }
            } else { // 编辑
                $checkBoxItem = '';
                $feeTypeArr = json_decode($form->model()->fee_type, true);
                $feeTypeOptions = Project::getFeeTypeOptions();
                foreach ($feeTypeOptions as $feeTypeID => $feeTypeName) {
                    $checkBoxItem .= '<div class="item" style="float: left; margin-right: 10px;">
                                    <div class="vs-checkbox-con vs-checkbox-primary" style="margin-right: 16px">
                                        <input value="' . $feeTypeID . '" name="fee_type[]" ' . (array_key_exists($feeTypeID, $feeTypeArr) ? 'checked' : '') . ' class="field_fee_type _normal_ Dcat_Admin_Widgets_Checkbox" type="checkbox" initialized="" id="' . time() . $feeTypeID . '">
                                        <span class="vs-checkbox vs-checkbox-">
                                            <span class="vs-checkbox--check">
                                                <i class="vs-icon feather icon-check"></i>
                                            </span>
                                        </span>
                                        <span>' . $feeTypeName . '</span>
                                    </div>
                                    <input type="text" name="fee_type_' . $feeTypeID . '" value="' . ($feeTypeArr[$feeTypeID] ?? '') . '" placeholder="请输入税后金额" >
                                </div>   ';
                }
            }

            $html = <<<HTML
        <div class="checkbox-container">
           $checkBoxItem
        </div>
        <script>
        $(function() {
            $("input[name='fee_type[]']").on('click', function () {
                if (!$(this).is(":checked")) {
                    $("input[name='fee_type_" + $(this).val() +"']").val('');
                }
            });
        });
        </script>
HTML;

            $form->html($html, '费用类型')->required();


            $form->display('created_at');
            $form->display('updated_at');

            $form->select('tpl_id', '协议模板')
                ->options(ContractTemplate::getTemplateList())
                ->required();

            $form->saving(function (Form $form) use ($feeTypeOptions) {

                foreach ($form->fee_type as $feeTypeID) {
                    if (!$form->{'fee_type_' . $feeTypeID}) {
                        return $form->response()->error('请输入' . $feeTypeOptions[$feeTypeID] . '税后金额');
                    }
                }

                if ($form->isCreating()) {
                    // 项目编码
                    $project_code = null;
                    while (true) {
                        $project_code = random_int(100000, 999999);
                        $rs = \App\Models\Project::where('project_code', $project_code)->first();
                        if (!$rs) {
                            break;
                        }
                    }
                    $form->project_code = $project_code;

                    // 创建人
                    $currLoginUser = auth('admin')->user();
                    $form->master_user_id = $currLoginUser->id;
                    $form->master_user_name = $currLoginUser->username;
                }
                $form->builder()->pushField(new Form\Field('fee_type'));
                $feeTypeJson = [];
                foreach ($form->fee_type as $v) {
                    $feeTypeJson[$v] = $form->{'fee_type_' . $v};
                }
                $form->fee_type = json_encode($feeTypeJson, '256');
            });
        });
    }
}
